// 评估价导入
<template>
  <basic-container>
    <v-step ref="steps" :milepost="milepost" templateUrl="/propertypriceImport.xls">
      <div slot="step1" v-if="importFail">
        <el-tabs v-model="activeName" class="importFail">
          <el-tab-pane :label="`总共添加(${rentPrices.length})`" name="first">
            <el-table :data="rentPrices" stripe>
              <el-table-column label="物业名称" prop="propertyName" width="300" />
              <el-table-column label="物业地址" prop="address" />
              <el-table-column prop="price" label="市场评估租金单价（元/m²/月）" width="200" />
            </el-table>
          </el-tab-pane>
          <el-tab-pane :label="`异常情况(${failData.length})`" name="second">
            <div class="failWrap">
              <div class="failTitle">
                <span>异常提示：</span>
                <el-button size="small" @click="exportFailData">导出异常数据</el-button>
              </div>
              <ul>
                <li v-for="(item, index) in failData" :key="index">{{item}}</li>
              </ul>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
      <div class="formWrap" slot="step1" v-else>
        <div class="card-title">基础信息</div>
        <el-form ref="formData" class="form-wrap" size="small" :rules="rules" :model="formData">
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="评估编号" prop="batch">
                <el-input v-halfCharCode v-model="formData.batch" placeholder="请输入" readonly />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="评估日期" prop="assessDate">
                <el-date-picker
                  v-model="formData.assessDate"
                  readonly
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  @change="dateVerify('assessDate')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="有效日期" prop="validDate">
                <el-date-picker
                  v-model="formData.validDate"
                  readonly
                  type="date"
                  value-format="yyyy-MM-dd"
                  placeholder="选择日期"
                  @change="dateVerify('validDate')"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="评估机构" prop="assessOrg">
                <el-input v-halfCharCode readonly v-model="formData.assessOrg" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <div class="card-title">物业信息</div>
        <el-table :data="rentPrices" stripe>
          <el-table-column label="物业名称" prop="propertyName" width="280">
            <template slot-scope="scope">
              <el-input v-halfCharCode v-model="scope.row.propertyName" readonly />
            </template>
          </el-table-column>
          <el-table-column label="物业地址" prop="address">
            <template slot-scope="scope">
              <el-input v-halfCharCode v-model="scope.row.address" readonly />
            </template>
          </el-table-column>
          <el-table-column prop="price" label="市场评估租金单价（元/m²/月）" width="200">
            <template slot-scope="scope">
              <el-input v-model="scope.row.price" controls-position="right" readonly v-only-number="{min:0,precision:2}" maxlength="15" />
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div class="formWrap" slot="step2">
        <div class="card-title">其他附件</div>
        <div class="uploadWrap">
          <p style="font-size: 14px;padding:20px 20px 0px;">
            评估资料
            <font color="red">*</font>
          </p>
          <v-upload ref="myUpload" modelType="rent-price" @onSuccess="onSuccess" v-model="uploadFileList" />
        </div>
      </div>
    </v-step>
  </basic-container>
</template>

<script>
import { batchImport, checkPropertyExcel, addRentPriceData, downloadPost } from "../api/rent-pricebatch"
import { downloadBlob } from "@/utils";
import moment from 'moment'

export default {
  data () {
    return {
      // 导入模板出错判断
      importFail: false,
      // 导入失败展示tab绑定值
      activeName: 'second',
      // 导入成功数据
      successData: [],
      // 导入失败数据
      failData: [],
      // 导出异常数据api参数
      exportParams: {},
      //基础信息
      formData: {
        batch: "",
        assessDate: '',
        validDate: '',
        assessOrg: ""
      },
      // 物业信息
      rentPrices: [],
      // 附件列表
      uploadFileList: [],
      // 基础信息校验
      rules: {
        batch: [
          { required: true, message: '请输入批次号', trigger: 'blur' },
          { min: 8, max: 20, message: '长度在 8 到 20 个字符' }
        ],
        assessDate: [
          { required: true, message: '请选择评估日期', trigger: 'blur' },
          { validator: this.validateAssessDate, trigger: 'blur' },
        ],
        validDate: [
          { required: true, message: '请选择有效时间', trigger: 'blur' },
          { validator: this.validateValidDate, trigger: 'blur' },
        ],
        assessOrg: [
          { required: true, message: '请输入评估机构', trigger: 'blur' },
          { min: 1, max: 20, message: '评估机构长度不能超过20个字符', trigger: 'blur' }
        ],
      },

    };
  },
  computed: {
    // 里程碑列表
    milepost () {
      return [
        { title: "选择模板", validate: this.handleStep1 },
        { title: "基础信息填写", validate: this.handleStep2 },
        { title: "上传文件", validate: this.handleStep3 },
      ];
    },
  },
  methods: {
    //附件上传成功监听
    async onSuccess (data) {
      try {
        const res = await addRentPriceData({ ...this.formData, rentPrices: this.rentPrices, rentPricebatchId: data.data || '' })
        if (res.data.code == 0) {
          this.$message.success("提交成功");
          //this.$router.back();
          this.$router.push({ path: '/wy-rent/price/graphic-list' })
        } else {
          this.$message.error("服务端异常：" + res.message);
        }
      } catch (error) {
        console.log(error)
      }
    },
    async handleStep1 () {
      // 重置上传失败数据
      this.importFail = false;
      this.successData.length = 0;
      this.failData.length = 0;
      this.exportParams = {};
      // 上传校验
      const fileList = this.$refs.steps.fileList;
      if (!fileList.length) {
        this.$message.error("请先上传物业信息模板");
      } else {
        let file = new FormData();
        file.append('file', fileList[0].raw)
        const res = await this.http.post('/api/rentpricebatch/import-check', file)
        if (res.data.code == 0) {
          const { ifOk, batch, assessDate, validDate, assessOrg, rentPriceImportVOS } = res.data.data
          if (!ifOk) {
            this.$message.error(res.data.data.errorMessage)
            return false
          } else {
            if (rentPriceImportVOS.every(i => i.ifOk)) {
              this.rentPrices = rentPriceImportVOS;
              this.formData = { batch, assessDate, validDate, assessOrg }
              return true;
            } else {
              let successData = [];
              let failData = [];
              rentPriceImportVOS.forEach((item, index) => {
                item.isOk ? successData.push(item) : failData.push(`第${index + 1}行：${item.errorMessage}`)
              })
              this.exportParams = res.data.data
              this.successData = successData
              this.failData = failData
              this.importFail = true
              return true;
            }
          }
        }
      }
      return false;
    },
    async handleStep2 () {
      if (this.importFail) {
        this.$message.error('上传数据存在异常，请重新上传')
        return false
      }
      try {
        let result = await this.$refs.formData.validate()
        return true
      } catch (error) {
        return false
      }
    },
    handleStep3 () {
      this.$refs.myUpload.submit();
    },
    // 导出异常数据
    exportFailData () {
      const time = new Date();
      const name = `${time.getFullYear()}-${time.getMonth() +
        1}-${time.getDate()} ${time.getHours()}:${time.getMinutes()}:${time.getSeconds()}导入异常数据.xlsx`;
      downloadPost({ ...this.exportParams }).then(res => {
        downloadBlob(res.data, name);
      })
    },
    // 监听步骤修改
    async handleStepChange (step) {
      //return true;
      switch (step) {
        case 0:
          const fileList = this.$refs.steps.fileList;
          if (!fileList.length) {
            this.$message.error("请先上传物业信息模板");
          } else {
            let file = new FormData();
            file.append('file', fileList[0].raw)
            const res = await this.http.post('/api/rentpricebatch/import-check', file)
            if (res.data.code == 0) {
              let failData = res.data.data.find(i => !i.ifOk)
              if (!failData) {
                this.rentPrices = res.data.data;
                return true;
              }
              this.$message.error(failData.errorMessage)
            }
          }
          return false;
        case 1:
          this.$refs["formData"].validate(validate => {

            return validate
          })
        default:
          return true;
      }
    },
    // 日期大小校验
    dateVerify (prop) {
      this.$refs.formData.validateField(prop)
    },
    // 评估日期校验
    validateAssessDate (rule, value, callback) {
      if (!this.formData.validDate) return callback();
      const startDate = moment(value, "YYYY-MM-DD")
      const endDate = moment(this.formData.validDate, "YYYY-MM-DD")
      let diffDay = endDate.diff(startDate, 'days')
      if (diffDay < 1) {
        return callback(new Error('评估日期必须小于有效日期'));
      }
      return callback();
    },
    // 有效时间校验
    validateValidDate (rule, value, callback) {
      if (!this.formData.assessDate) return callback();
      const startDate = moment(this.formData.assessDate, "YYYY-MM-DD")
      const endDate = moment(value, "YYYY-MM-DD")
      let diffDay = endDate.diff(startDate, 'days')
      if (diffDay < 1) {
        return callback(new Error('有效日期必须大于评估日期'));
      }
      return callback();
    },
  },
};
</script>

<style scoped lang="scss">
.card-title {
  margin-bottom: 10px;
}
.uploadWrap {
  width: 800px;
  min-height: 200px;
  display: flex;
  justify-content: flex-start;
}
.importFail {
  padding: 0 60px;
}
.failWrap {
  min-height: 300px;
  .failTitle {
    display: flex;
    justify-content: space-between;
    align-items: center;
    > span {
      color: #f00;
      font-size: 16px;
    }
  }
  ul > li {
    line-height: 1.5;
    margin-top: 10px;
    color: #f00;
    font-size: 14px;
    text-align: left;
  }
}
</style>
